package com.zggk.iroad.Distribution.distributionlist;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zggk.iroad.Distribution.distributionmx.DistributionMxActivity;
import com.zggk.iroad.R;
import com.zggk.iroad.api.MyAppliCation;
import com.zggk.iroad.diease.dieaselist.DistriListBean;
import com.zggk.iroad.log.LogSuccessBean;
import com.zggk.iroad.mvp.MVPBaseActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class DistributionListActivity extends MVPBaseActivity<DistributionListContract.View, DistributionListPresenter> implements DistributionListContract.View {


    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.time_te)
    TextView timeTe;
    @Bind(R.id.month_layout)
    LinearLayout monthLayout;
    @Bind(R.id.lay_xm)
    LinearLayout layXm;
    @Bind(R.id.log_rv)
    ListView listView;
    @Bind(R.id.sm_lay)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.add_lay)
    TextView addLay;
    private DistriAdapter adapter;
    private String LXID;
    private String BHLX;
    private String DATAID;
    private String ACTION;
    private ArrayList<DistriListBean.BHLISTBean> Datas = new ArrayList<>();
    private OptionsPickerView PickerView;
    private List<String> pickerData = new ArrayList<>();
    private String GZZLBH;
    private ArrayList<DistriListBean.BHLISTBean> UpDatas = new ArrayList<>();

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_distri_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mPresenter.getDH();
        initAdapter();
        initView();
        initData();
    }

    private void initData() {
        refreshLayout.autoRefresh();
    }

    private void initView() {
        titleText.setText("审核派发");
        pickerData.add("派发");
        pickerData.add("不处置");
        pickerData.add("纳入大中修");
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                ACTION = "0";
                DATAID = "0";
                mPresenter.testinfo(LXID, BHLX, DATAID, ACTION);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                ACTION = "1";
                if (Datas != null && Datas.size() > 0) {
                    ACTION = Datas.get(Datas.size() - 1).getBHID();
                }
                mPresenter.testinfo(LXID, BHLX, DATAID, ACTION);
            }
        });
    }

    private void initAdapter() {
        adapter = new DistriAdapter(DistributionListActivity.this, Datas, true);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(DistributionListActivity.this, DistributionMxActivity.class);
                intent.putExtra("RZID", Datas.get(position).getBHID());
                startActivity(intent);
            }
        });
    }

    @Override
    public void getDhs(DhBean videoVos) {
        GZZLBH = videoVos.getRWDH();
    }

    @Override
    public void getData(DistriListBean videoVos) {
        if (refreshLayout.isLoadmoreFinished()) {
            refreshLayout.setLoadmoreFinished(false);
        }
        if (videoVos.getBHLIST() != null && videoVos.getBHLIST().size() > 0) {
            ArrayList<Boolean> listSelTag = adapter.getListSelectTag();
            if ("0".equals(ACTION)) {
                Datas.clear();
                listSelTag.clear();
            }
            Datas.addAll(videoVos.getBHLIST());
            for (int i = 0; i < Datas.size(); i++) {
                if (i >= listSelTag.size()) {
                    listSelTag.add(false);
                }
            }
            adapter.setListSelectTag(listSelTag);
            adapter.notifyDataSetChanged();
            if (videoVos.getBHLIST().size() < 20) {
                refreshLayout.setLoadmoreFinished(true);
            }
        } else {
            adapter.notifyDataSetChanged();
            refreshLayout.setLoadmoreFinished(true);
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
    }

    @Override
    public void getPaifas(LogSuccessBean videoVos) {
        ToastUtils.showShort("请求成功");
        refreshLayout.autoRefresh();
    }

    @Override
    public void getBczs(LogSuccessBean videoVos) {
        ToastUtils.showShort("请求成功");
        refreshLayout.autoRefresh();
    }

    @Override
    public void getNr(LogSuccessBean videoVos) {
        ToastUtils.showShort("请求成功");
        refreshLayout.autoRefresh();
    }

    @OnClick({R.id.back, R.id.month_layout, R.id.add_lay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.month_layout:
                TimePickerView ksTimes = new TimePickerView.Builder(DistributionListActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        timeTe.setText(new SimpleDateFormat("yyyy-MM-dd").format(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                ksTimes.setDate(Calendar.getInstance());
                ksTimes.show();
                break;
            case R.id.add_lay:
                //派发单单信息（JLDW：当前登陆单位id，RWXDSJ:任务派发时间，YQWCSJ:要求完成时间,PFR:派发人,CREATOR:当前登陆人,GZZLBH:派发单号）
                PickerView = new OptionsPickerView.Builder(DistributionListActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        if (pickerData.get(options1).equals("派发")) {
                            if (StringUtils.isEmpty(timeTe.getText().toString())) {
                                ToastUtils.showShort("请添加要求完成时间");
                                return;
                            }
                            DistriJson distriJson = new DistriJson();
                            distriJson.setJLDW(MyAppliCation.spUtils.getString("GydwId"));
                            distriJson.setRWXDSJ(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                            distriJson.setYQWCSJ(timeTe.getText().toString());
                            distriJson.setPFR(MyAppliCation.spUtils.getString("OrgName"));
                            distriJson.setCREATOR(MyAppliCation.spUtils.getString("OrgName"));
                            distriJson.setGZZLBH(GZZLBH);
                            String json = new Gson().toJson(distriJson);
                            UpDatas = getSelectInfoData();
                            String bhStr = "";
                            for (int i = 0; i < UpDatas.size(); i++) {
                                DistriListBean.BHLISTBean info = UpDatas.get(i);
                                if (i == UpDatas.size() - 1) {
                                    bhStr += info.getBHID();
                                } else {
                                    bhStr += info.getBHID() + ",";
                                }
                            }
                            mPresenter.getPaifa(json, bhStr);
                        } else if (pickerData.get(options1).equals("不处置")) {
                            String bhguid = "";
                            for (int i = 0; i < UpDatas.size(); i++) {
                                DistriListBean.BHLISTBean info = UpDatas.get(i);
                                if (i == UpDatas.size() - 1) {
                                    bhguid += info.getBHID();
                                } else {
                                    bhguid += info.getBHID() + ",";
                                }
                            }
                            String bhzt = "13";
                            String user = MyAppliCation.spUtils.getString("OrgName");
                            mPresenter.getBcz(bhguid, bhzt, user);
                        } else if (pickerData.get(options1).equals("纳入大中修")) {
                            String bhguid = "";
                            for (int i = 0; i < UpDatas.size(); i++) {
                                DistriListBean.BHLISTBean info = UpDatas.get(i);
                                if (i == UpDatas.size() - 1) {
                                    bhguid += info.getBHID();
                                } else {
                                    bhguid += info.getBHID() + ",";
                                }
                            }
                            String bhzt = "14";
                            String user = MyAppliCation.spUtils.getString("OrgName");
                            mPresenter.getNr(bhguid, bhzt, user);
                        }
                    }
                }).setLayoutRes(R.layout.select_lay, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                PickerView.returnData();
                                PickerView.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                PickerView.dismiss();
                            }
                        });
                    }
                }).build();
                PickerView.setPicker(pickerData);
                PickerView.show();
                break;
        }
    }

    /**
     * @Description: (获取选择某一项)
     * @author 张成昆
     * @date 2019-8-23
     */
    private ArrayList<DistriListBean.BHLISTBean> getSelectInfoData() {
        ArrayList<DistriListBean.BHLISTBean> listResult = new ArrayList<>();
        ArrayList<Boolean> listSelTag = adapter.getListSelectTag();
        boolean isStateSame = true;
        if (listSelTag != null && listSelTag.size() > 0) {
            if (listSelTag.size() == Datas.size()) {
                for (int i = 0; i < listSelTag.size(); i++) {
                    DistriListBean.BHLISTBean info = Datas.get(i);
                    String bhzt = info.getBHZT();
                    if (listSelTag.get(i)) {
                        listResult.add(info);
                        if (!"2".equals(bhzt) && !"1".equals(bhzt)) {
                            isStateSame = false;
                        }
                    }
                }
            }
        }
        if (listResult.size() > 0) {
            if (isStateSame) {
                return listResult;
            } else {
                ToastUtils.showShort("只有新添加和新病害可以派发，请重新选择");
                return null;
            }
        } else {
            ToastUtils.showShort("请选择病害");
            return null;
        }
    }
}
